//
//  UIButton.swift
//  fho
//
//  Created by 郭颢源 on 2021/4/1.
//

import Foundation
import UIKit

/// image 相对title的位置枚举
enum ButtonEdgeInsetsStyle {
    case top // image在上，label在下
    case left  // image在左，label在右
    case bottom  // image在下，label在上
    case right // image在右，label在左
}

extension UIButton {
    
    /// 设置image，title 布局
    /// - Parameters:
    ///   - style: image 相对title的位置
    ///   - space: image 与 title 间距
    func layoutButtonEdgeInsets(style:ButtonEdgeInsetsStyle,space:CGFloat) {
        var labelWidth : CGFloat = 0.0
        var labelHeight : CGFloat = 0.0
        var imageEdgeInset = UIEdgeInsets.zero
        var labelEdgeInset = UIEdgeInsets.zero
        let imageWith = self.imageView?.frame.size.width
        let imageHeight = self.imageView?.frame.size.height
        let vue = (UIDevice.current.systemVersion) as NSString
        
        if vue.doubleValue >= 8.0 {
            
            labelWidth = (self.titleLabel?.intrinsicContentSize.width)!
            labelHeight = (self.titleLabel?.intrinsicContentSize.height)!
        }else {
            labelWidth = (self.titleLabel?.frame.size.width)!
            labelHeight = (self.titleLabel?.frame.size.height)!
        }
        
        switch style {
        case .top:
            imageEdgeInset = UIEdgeInsets(top: -labelHeight-space/2.0, left: 0, bottom: 0, right: -labelWidth)
            labelEdgeInset = UIEdgeInsets(top: 0, left: -imageWith!, bottom: -imageHeight!-space/2.0, right: 0)
        case .left:
//            imageEdgeInset = UIEdgeInsets(top: 0, left: -space/2.0, bottom: 0, right: space/2.0);
//            labelEdgeInset = UIEdgeInsets(top: 0, left: space/2.0, bottom: 0, right: -space/2.0);
            if self.contentHorizontalAlignment == .left {
                labelEdgeInset = UIEdgeInsets.init(top: 0, left: space, bottom: 0, right: 0)
            } else if self.contentHorizontalAlignment == .right {
                imageEdgeInset = UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: space)
            } else {
                let spacing_half = 0.5 * space;
                imageEdgeInset = UIEdgeInsets.init(top: 0, left: -spacing_half, bottom: 0, right: spacing_half)
                labelEdgeInset = UIEdgeInsets.init(top: 0, left: spacing_half, bottom: 0, right: -spacing_half)
            }
        case .bottom:
            imageEdgeInset = UIEdgeInsets(top: 0, left: 0, bottom: -labelHeight-space/2.0, right: -labelWidth)
            labelEdgeInset = UIEdgeInsets(top: -imageHeight!-space/2.0, left: -imageWith!, bottom: 0, right: 0)
        case .right:
            // To Do print("坐标是====\(labelWidth)=====\(space)")
//            imageEdgeInset = UIEdgeInsets(top: 0, left: labelWidth+space/2.0, bottom: 0, right: -labelWidth-space/2.0)
//            labelEdgeInset = UIEdgeInsets(top: 0, left: -imageWith!-space/2.0, bottom: 0, right: imageWith!+space/2.0)
            
            if self.contentHorizontalAlignment == .left {
                imageEdgeInset = UIEdgeInsets.init(top: 0, left: labelWidth + space, bottom: 0, right: 0)
                labelEdgeInset = UIEdgeInsets.init(top: 0, left: -imageWith!, bottom: 0, right: 0)
            } else if self.contentHorizontalAlignment == .right {
                imageEdgeInset = UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: -labelWidth)
                labelEdgeInset = UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: imageWith! + space)
            } else {
                let imageOffset = labelWidth + 0.5 * space
                let titleOffset = imageWith! + 0.5 * space
                imageEdgeInset = UIEdgeInsets.init(top: 0, left: imageOffset, bottom: 0, right: -imageOffset)
                labelEdgeInset = UIEdgeInsets.init(top: 0, left: -titleOffset, bottom: 0, right: titleOffset)
            }
            
        }
        self.titleEdgeInsets = labelEdgeInset
        self.imageEdgeInsets = imageEdgeInset
    }
    
    ///
    /// Set image location
    ///
    /// Image and title must be set before this method will work, It is recommended to set it inside the block
    ///
    /// - parameter location: location of image relative to title
    /// - parameter space: space between image and title
    /// - parameter completion: set image and title
    ///
    func sg_setImage(style: ButtonEdgeInsetsStyle, space: CGFloat, completion: (UIButton) -> ()) {
        completion(self)
        layoutButtonEdgeInsets(style: style, space: space)
    }
    
    /// 在点击事件中设置，连续点击按钮的时间间隔
    /// - Parameter time: 时间间隔
    func sg_timeInterval(time: TimeInterval) {
        self.isUserInteractionEnabled = false
        DispatchQueue.main.asyncAfter(deadline: .now() + time) {
            self.isUserInteractionEnabled = true
        }
    }
    ///
    /// Send SMS verification code
    ///
    /// The countdown time is in seconds
    ///
    /// - parameter second: Count down time
    /// - parameter front: Text before number
    /// - parameter behind: Text after number
    /// - parameter end: Button title after completion
    /// - parameter completion: Completed Block
    ///
    func sg_sendSMSVerification(second: Int, front: String, behind: String, end: String, completion: (() -> ())?) {
        var tempSecond = second
        
        let queue = DispatchQueue.global()
        let timer = DispatchSource.makeTimerSource(flags: [], queue: queue)
        timer.schedule(deadline: .now(), repeating: .seconds(1))
        timer.setEventHandler {
            if tempSecond <= 1 {
                timer.cancel()
                DispatchQueue.main.async {
                    self.isEnabled = true
                    self.setTitle("\(end)", for: .normal)
                    if completion != nil {
                        completion!()
                    }
                }
            } else {
                tempSecond -= 1;
                DispatchQueue.main.async {
                    self.isEnabled = false
                    self.setTitle("\(front)\(tempSecond)\(behind)", for: .normal)
                }
            }
        }
        timer.resume()
    }
    
    
}


